package com.dujiu.utils;

import com.dujiu.config.JwtConfig;
import com.dujiu.pojo.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {
    private final JwtConfig jwtConfig;

    private JwtUtil(JwtConfig jwtConfig){
        this.jwtConfig = jwtConfig;
    }

    public String createToken(User user) {
        // 定义header部分内容
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtConfig.getSecret())
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtConfig.getTokenTime()))
                .compact();
    }

    // 判断token是否过期
    public boolean validateToken(String token) {
        Claims claims = getClaimsFormToken(token);
        Date expiration = claims.getExpiration();
        return expiration.after(new Date()); // 判读过期时间是否在当前时间之后
    }

    // 从token里获取claims
    public Claims getClaimsFormToken(String token) {
        return Jwts.parser()
                .setSigningKey(jwtConfig.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    // username
    public String getUsernameFormClaims(String token){
        return getClaimsFormToken(token).getSubject();
    }
}
